<?php

/**
 * 客户列表
 * @Author: wjf
 * @Date: 2022-11-25 19:04:31 
 * */

namespace app\crm\controller\client;

use app\crm\model\client\Ourclients as ModelClientOurclients;
use app\crm\validate\client\Ourclients as ClientOurclients;
use think\Controller;
use think\facade\Session;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\db\Where;

class Ourclients extends Controller
{
    /**
     * 主页面 
     * @Author: wjf
     * @Date: 2022-11-26 15:53:32
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 添加页面
     * @Author: wjf
     * @Date: 2022-11-26 15:53:22
     */
    public function add()
    {
        return $this->fetch();
    }
    /**
     * 添加插入数据库
     * @Author: wjf
     * @Date: 2022-11-26 15:53:50
     */
    public function data()
    {
        //1、验证请求方式
        if ($this->request->isPost() && $this->request->isAjax()) {
            //2、获取数据
            $data = $this->request->post();
            //3、验证数据
            $validata = new ClientOurclients();
            if ($validata->check($data) == false) {
                $this->error($validata->getError());
            }
            //、数据库操作
            $OuModel = new ModelClientOurclients();
            if ($OuModel->save($data)) {
                return json(['code' => 1, 'msg' => '添加成功']);
            } else {
                return json(['code' => 0, 'msg' => '添加失败']);
            }
        }
    }

    /**
     * 数据，分页
     * @Author: wjf
     * @Date: 2022-11-19 17:19:17
     */
    public function list()
    {
        if ($this->request->param('data')) {
            $aa = $this->request->get('data');
            $arr = [];
            foreach ($aa as $k => $v) {
                if (!$v) {
                    unset($aa[$k]);
                } else {
                    $arr[$k] = $v;
                }
            }
            $page = ($_GET['page'] - 1) * $_GET['limit'];
            $data = ModelClientOurclients::where($arr)->where('status', 2)->where('super_id', 1)->where('classify', 1)->select();
            $count = ModelClientOurclients::where('classify', 1)->where('status', 2)->where('super_id', 1)->count();
            return json(['code' => 0, 'msg' => '遍历', 'count' => $count, 'data' => $data]);
        } else {
            $page = ($_GET['page'] - 1) * $_GET['limit'];
            $data = ModelClientOurclients::limit($page, $_GET['limit'])->where('status', 2)->where('super_id', 1)->where('classify', 1)->select();
            $count = ModelClientOurclients::where('classify', 1)->where('status', 2)->where('super_id', 1)->count();
            return json(['code' => 0, 'msg' => '遍历', 'count' => $count, 'data' => $data]);
        }
    }

    /**
     * 遍历数据
     * @Author: wjf
     * @Date: 2022-11-26 18:28:36
     */
    public function edit()
    {
        if (!empty($_GET['id'])) {
            Session::set('e_id', $_GET['id']);
            $list = ModelClientOurclients::where('id', $_GET['id'])->select();
            $this->assign(['list' => $list]);
        }
        return $this->fetch();
    }

    /**
     * 跟新
     * @Author: wjf
     * @Date: 2022-11-27 21:58:02
     */
    public function amend()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $data = $this->request->post();
            $ModelClientOurclients = new ModelClientOurclients;
            if ($ModelClientOurclients->allowField(true)->isUpdate(true)->save($data, ['id' => Session::get('e_id')])) {
                return json(['code' => 1, 'msg' => '跟新成功']);
            } else {
                return json(['code' => 0, 'msg' => '跟新失败']);
            }
        }
    }

    /**
     * 导入
     * @Author: wjf
     * @Date: 2022-11-29 18:19:42
     */
    public function tolead()
    {
        return $this->fetch();
    }

    /**
     * 下载模板 
     * @Author: wjf
     * @Date: 2022-11-30 14:41:09
     */
    public function  download()
    {
        $title = ['名称', '手机', '电话', '级别', '行业', '来源', '标签', '地址', '详细地址', '下次跟进时间', '备注', '业务员id', '负责人id', '状态', '分类', '领取时间', '创建时间', '修改时间'];

        $spreadsheet = new Spreadsheet;
        $sheet = $spreadsheet->getActiveSheet();

        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            //单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        //保存
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $fileName = 'demo.xlsx';
        //输出到浏览器
        header('Content-type: text/html; charset=utf-8');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }

    /**
     * 返回文件所在目录 
     * @Author: wjf
     * @Date: 2022-11-30 18:10:24
     */
    public function uploading()
    {
        if ($this->request->isAjax()) {
            // 获取表单上传文件 例如上传了001.xlsx          
            $file = request()->file('file');

            // 移动到框架应用根目录/upload/ 目录下
            $info = $file->validate(['ext' => 'xlsx'])->move('static/upload');
            if ($info) {
                // // 成功上传后 获取上传信息
                // // 输出 jpg
                // echo $info->getExtension();
                // // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                // echo $info->getSaveName();
                // // 输出 42a79759f284b767dfcb2a0197904287.jpg
                // echo $info->getFilename();
                $path = 'D:\phpEnv\www\localhost\crm\public\static\upload\/' . $info->getSaveName();
                return json(['code' => 1, 'msg' => '成功上传', 'data' => ['text' => $path]]);
            } else {
                // 上传失败获取错误信息
                return json(['code' => 0, 'msg' => $file->getError(), 'data' => []]);
            }
        }
    }

    /**
     * 上传数据库
     * @Author: wjf
     * @Date: 2022-11-30 20:13:45
     */
    public function uploadingSql()
    {
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($_POST['title']); //载入Xlsx表格
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数
        $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow;
        if ($lines <= 1) {
            return json(['code' => 0, 'msg' => 'xlsx表格中没有数据']);
        }

        $sql = "INSERT INTO `crm_client` (`name`, `phone`, `landline`, `grade`,`industry`,`source`,`label`,`address`,`detailed`,`follow_time`,`remark`,`sale_id`,`super_id`,`status`,`classify`,`get_time`,`create_time`,`update_time`) VALUES ";

        for ($row = 2; $row <= $highestRow; $row++) {
            $name = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
            $chinese = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
            $maths = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
            $english = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
            $a = $worksheet->getCellByColumnAndRow(5, $row)->getValue();
            $b = $worksheet->getCellByColumnAndRow(6, $row)->getValue();
            $c = $worksheet->getCellByColumnAndRow(7, $row)->getValue();
            $d = $worksheet->getCellByColumnAndRow(8, $row)->getValue();
            $e = $worksheet->getCellByColumnAndRow(9, $row)->getValue();
            $f = $worksheet->getCellByColumnAndRow(10, $row)->getValue();
            $g = $worksheet->getCellByColumnAndRow(11, $row)->getValue();
            $h = $worksheet->getCellByColumnAndRow(12, $row)->getValue();
            $y = $worksheet->getCellByColumnAndRow(13, $row)->getValue();
            $j = $worksheet->getCellByColumnAndRow(14, $row)->getValue();
            $k = $worksheet->getCellByColumnAndRow(15, $row)->getValue();
            $l = $worksheet->getCellByColumnAndRow(16, $row)->getValue();
            $m = $worksheet->getCellByColumnAndRow(17, $row)->getValue();
            $q = $worksheet->getCellByColumnAndRow(18, $row)->getValue();
            $sql .= "('$name','$chinese','$maths','$english','$a','$b','$c','$d','$e','$f','$g','$h','$y','$j','$k','$l','$m','$q'),";
        }
        $sql = rtrim($sql, ","); //去掉最后一个,号
        // 启动事务
        Db::startTrans();
        try {
            ModelClientOurclients::query($sql);
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '成功上传']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '上传失败']);
        }
    }

    /**
     * 放入公海
     * @Author: wjf
     * @Date: 2022-12-06 09:31:17
     */
    public function putin()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            if (ModelClientOurclients::where('id', $_POST['id'])->update(['super_id' => 0, 'status' => 0, 'classify' => 0])) {
                return json(['code' => 0, 'msg' => '放入成功']);
            }
        }
    }

    /**
     * 放入公海多个
     * @Author: wjf
     * @Date: 2022-12-06 09:38:57
     */
    public function putind()
    {
        // 启动事务
        Db::startTrans();
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $_POST['id'];
            $arr = explode(',', $id);
            array_pop($arr);
            try {
                foreach ($arr as $k => $v) {
                    ModelClientOurclients::where('id', $v)->update(['super_id' => 0, 'status' => 0, 'classify' => 0]);
                }
                // 提交事务
                Db::commit();
                return json(['code' => 0, 'msg' => '领取成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 1, 'msg' => '领取失败']);
            }
        }
    }

    /**
     * 软删除
     * @Author: wjf
     * @Date: 2022-12-06 14:14:11
     */
    public function del()
    {
        if ($this->request->isGet() && $this->request->isAjax()) {
            if (ModelClientOurclients::destroy($_GET['id'])) {
                return json(['code' => 0, 'msg' => '删除成功']);
            }
        }
    }

    /**
     * 回收站 
     * @Author: wjf
     * @Date: 2022-12-06 14:22:28
     */
    public function recycle()
    {
        if ($this->request->isGet() && $this->request->isAjax()) {
            $page = ($_GET['page'] - 1) * $_GET['limit'];
            $data = ModelClientOurclients::onlyTrashed()->limit($page, $_GET['limit'])->select();
            $count = ModelClientOurclients::onlyTrashed()->count();
            return json(['code' => 0, 'msg' => '遍历', 'count' => $count, 'data' => $data]);
        }
        return $this->fetch();
    }

    /**
     * 还原全部
     * @Author: wjf
     * @Date: 2022-12-06 14:49:06
     */
    public function restoreqb()
    {
        // 启动事务
        Db::startTrans();
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = ModelClientOurclients::onlyTrashed()->select();
            try {
                foreach ($id as $v) {
                    ModelClientOurclients::onlyTrashed()->find($v['id'])->restore();
                }
                // 提交事务
                Db::commit();
                return json(['code' => 0, 'msg' => '还原成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => '还原失败']);
            }
        }
    }

    /**
     * 还原
     * @Author: wjf
     * @Date: 2022-12-06 15:16:20
     */
    public function restore()
    {
        // 启动事务
        Db::startTrans();
        if ($this->request->isPost() && $this->request->isAjax()) {
            if (ModelClientOurclients::onlyTrashed()->find($_POST['id'])->restore()) {
                return json(['code' => 0, 'msg' => '还原成功']);
            }
        } else if ($this->request->isGet() && $this->request->isAjax()) {
            $arr = explode(',', $_GET['id']);
            array_pop($arr);
            try {
                foreach ($arr as $k => $v) {
                    ModelClientOurclients::onlyTrashed()->find($v)->restore();
                }
                // 提交事务
                Db::commit();
                return json(['code' => 0, 'msg' => '还原成功']);
            } catch (\Throwable $th) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => '还原失败']);
            }
        }
        return '1';
    }
}
